#include "push_init.h"

extern void (*ori_execute_ex)(zend_execute_data *execute_data);
extern void (*ori_execute_internal)(zend_execute_data *execute_data, zval *return_value);

extern client *client::instance;

client *pushgateway_client;

void init_minit()
{
    // 初始化客户端实例
    pushgateway_client = client::newInstance();

    // 监控自定义类方法
    ori_execute_ex = zend_execute_ex;
    zend_execute_ex = push_execute_ex;

    // 监控内置类方法
    ori_execute_internal = zend_execute_internal;
    zend_execute_internal = push_execute_internal;
}

void init_rinit()
{
    int internal = PUSHGATEWAY_G(interval);
        pushgateway_client = client::newInstance();
    pushgateway_client->run(internal);
}

void init_mshutdown()
{
    pushgateway_client = client::newInstance();
    pushgateway_client->syncSend();
}

void init_rshutdown()
{
    if (PUSHGATEWAY_G(debug))
    {
        pushgateway_client = client::newInstance();
        pushgateway_client->debug = true;
        pushgateway_client->output = PUSHGATEWAY_G(output);
    }
}

// 获取请求参数
string server_param(string name)
{
    char *namec = const_cast<char *>(name.c_str());
    zval *carrier = nullptr;
    zval *param;

    zend_bool jit_initialization = PG(auto_globals_jit);

    if (jit_initialization)
    {
        zend_string *server_str = zend_string_init("_SERVER", sizeof("_SERVER") - 1, 0);
        zend_is_auto_global(server_str);
        zend_string_release(server_str);
    }
    carrier = zend_hash_str_find(&EG(symbol_table), ZEND_STRL("_SERVER"));
    param = zend_hash_str_find(Z_ARRVAL_P(carrier), namec, name.length());

    string res = param == nullptr ? "" : to_string(Z_LVAL_P(param));

    return res;
}